package com.tanhua.admin.service;

import cn.hutool.core.collection.CollUtil;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.tanhua.commons.utils.Constants;
import com.tanhua.dubbo.api.MovementApi;
import com.tanhua.dubbo.api.UserInfoApi;
import com.tanhua.dubbo.api.VideoApi;
import com.tanhua.model.domain.FreezeDetail;
import com.tanhua.model.domain.UserInfo;
import com.tanhua.model.mongo.Movement;
import com.tanhua.model.mongo.Video;
import com.tanhua.model.vo.MovementsVo;
import com.tanhua.model.vo.PageResult;
import com.tanhua.model.vo.VideoVo;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Service
public class ManageService {

    @DubboReference
    private UserInfoApi userInfoApi;

    @DubboReference
    private VideoApi videoApi;

    @DubboReference
    private MovementApi movementApi;


    @Autowired
    private RedisTemplate<String, String> redisTemplate;


    //分页查询所有的数据
    public PageResult findAllUsers(int page, int pagesize) {
        //1、调用API分页查询数据列表  IPage
        IPage<UserInfo> iPage = userInfoApi.findAll(page, pagesize);
        List<UserInfo> list = iPage.getRecords();
        for (UserInfo userInfo : list) {
            String redisKey = Constants.USER_FREEZE + "_" + userInfo.getId().toString();
            //判断redis中是否存在这个key
            Boolean hasKey = redisTemplate.hasKey(redisKey);
            //更新
            if (hasKey) {
                userInfo.setUserStatus("2");
                userInfoApi.update(userInfo);
            } else {
                userInfo.setUserStatus("1");
                userInfoApi.update(userInfo);
            }
        }
        //2、转化为PageResult
        return new PageResult(page, pagesize, iPage.getTotal(), list);
    }


    //根据id查询用户资料

    public UserInfo findUserById(Long id) {
        UserInfo userInfo = userInfoApi.findById(id);
        String redisKey = Constants.USER_FREEZE + "_" + userInfo.getId().toString();
        //判断redisz中有没有这个key
        Boolean hasKey = redisTemplate.hasKey(redisKey);
        //更新userInfor
        if (hasKey) {
            userInfo.setUserStatus("2");
            userInfoApi.update(userInfo);
        } else {
            userInfo.setUserStatus("1");
            userInfoApi.update(userInfo);
        }
        return userInfo;
    }


    //查询视频分页列表
    public PageResult findVideosByUserId(Long uid, int page, int pagesize) {
        //1、调用videoApi服务，查询分页视频列表 ：PageResult -- List<Video>
        PageResult result = videoApi.findByUserId(uid, page, pagesize);
        //2、获取PageResult中的数据集合List<Video>
        List<Video> items = (List<Video>) result.getItems();
        if (CollUtil.isEmpty(items)) {
            return result;
        }
        //3、一个Video构造一个VideoVo   List<VideoVo>
        List<Long> userIds = CollUtil.getFieldValues(items, "userId",
                Long.class); //所有视频作者id
        Map<Long, UserInfo> map = userInfoApi.findByIds(userIds, null);//所有视频作者对象
        List<VideoVo> vos = new ArrayList<>();
        for (Video video : items) {
            //通过视频作者的id从map集合中获取，当前视频作者信息
            UserInfo userInfo = map.get(video.getUserId());
            if (userInfo != null) {
                vos.add(VideoVo.init(userInfo, video));
            }
        }
        //4、替换PageResult中的数据集合
        result.setItems(vos);
        return result;
    }

    //分页查询动态列表 movementvo
    public PageResult findMovementByUserId(Long uid, Integer state, int page, int pagesize) {
        //1、调用API分页查询  PageResult -- List<Movement>
        PageResult result = movementApi.findMovement(uid, state, page, pagesize);
        //2、获取PageResult中的数据集合List<Movement>
        List<Movement> items = (List<Movement>) result.getItems();
        if (CollUtil.isEmpty(items)) {
            return result;
        }
        //3、一个Movement构造一个MovementVo   List<Movement>
        List<Long> userIds = CollUtil.getFieldValues(items, "userId", Long.class); //所有视频作者id
        Map<Long, UserInfo> map = userInfoApi.findByIds(userIds, null);//所有视频作者对象
        List<MovementsVo> vos = new ArrayList<>();
        for (Movement movement : items) {
            UserInfo userInfo = map.get(movement.getUserId());
            if (userInfo != null) {
                vos.add(MovementsVo.init(userInfo, movement));
            }
        }
        //4、替换PageResult中的数据集合
        result.setItems(vos);
        return result;
    }

    //用户冻结 冻结时间，1为冻结3天，2为冻结7天，3为永久冻结
    //        冻结范围，1为冻结登录，2为冻结发言，3为冻结发布动态
    public String saveFreeze(FreezeDetail freezeDetail) {

        String redisKey = Constants.USER_FREEZE + "_" + freezeDetail.getUserId().toString();

        Boolean hasKey = redisTemplate.hasKey(redisKey);
        if (hasKey) {
            return "操作失败";
        }
        freezeDetail.setCreated(new Date());
        //获取冻结时间类型
        Integer time = freezeDetail.getFreezingTime();
        //把对象转换成josn字符串
        String freeze = JSON.toJSONString(freezeDetail);
        //把对象信息保存到redis中
        redisTemplate.opsForValue().set(redisKey, freeze);
        //判断冻结时间类型 设置redis中储存的对象过期时间  来实现到点自动删除
        if (time == 1) {
            redisTemplate.expire(redisKey, 3, TimeUnit.DAYS);
        } else if (time == 2) {
            redisTemplate.expire(redisKey, 7, TimeUnit.DAYS);
        } else {
            redisTemplate.expire(redisKey, 1000000000, TimeUnit.DAYS);
        }
        return "操作成功";
    }

    //取消冻结用户
    public String unfreeze(Map map) {
        //获取请求参数
        String userId = map.get("userId").toString();
        String redisKey = Constants.USER_FREEZE + "_" + userId;
        //判断redis中是否存在需要的数据
        Boolean hasKey = redisTemplate.hasKey(redisKey);
        if (!hasKey) {
            return "操作失败";
        }
        //存在删除
        redisTemplate.delete(redisKey);
        return "操作成功";

    }

    public String pass(String[] movementIds) {
        for (String movementId : movementIds) {
            movementApi.updateState(movementId,1);
        }
        return "pass";
    }

    public String reject(String[] movementIds) {
        for (String movementId : movementIds) {
            movementApi.updateState(movementId,2);
        }
        return "reject";
    }
}
